package com.appengine.news.ui.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.http.HttpServletRequest;

import com.appengine.news.entity.RssItemEntity;
import com.appengine.news.ui.model.RendererModel;
import com.appengine.news.utils.StringUtils;

/**
 * HTML plain renderer
 * 
 * @author Aliaksandr_Spichakou
 * 
 */
public class RendererController extends ReadController {
	/**
	 * 
	 */
	private static final long serialVersionUID = -4808097336665501824L;
	private static final Logger log = Logger.getLogger(RendererController.class
			.getName());
	private List<RendererModel> models = new ArrayList<RendererModel>();
	
	public RendererController(HttpServletRequest request) {
		super(request);
	}

	@Override
	public void doJob() {
		log.entering(RendererController.class.getName(), "doJob");
		final String ids = request.getParameter(VALUE_IDS);
		if (StringUtils.isEmpty(ids)) {
			log.log(Level.SEVERE, "Ids of items to render is empty");
			return;
		}
		final String[] split = ids.split(",");
		
		for (int i = 0; i < split.length; i++) {
			final String idStr = split[i];
			final Long parseString2Long = StringUtils.parseString2Long(idStr);
			if (parseString2Long == null) {
				log.log(Level.SEVERE, "Given ID is wrong: " + parseString2Long);
				continue;
			}
			final RssItemEntity item = findItem(parseString2Long);
			if(item==null)
			{
				log.log(Level.SEVERE, "Given ID is wrong, item not found: " + parseString2Long);
				continue;
			}
			final RendererModel model = new RendererModel();
			fillModel(item, model);
			models.add(model);
		}
		log.exiting(RendererController.class.getName(), "doJob");

	}
	/**
	 * Find RSS Item
	 * @param id
	 * @return
	 */
	private RssItemEntity findItem(Long id) {
		log.entering(RendererController.class.getName(), "findItem");
		final String query = "select from " + RssItemEntity.class.getName()
				+ " where id==" + id;
		final PersistenceManager pm = getPersistenceManager();
		final Query newQuery = pm.newQuery(query);

		final List<RssItemEntity> items = (List<RssItemEntity>) newQuery
				.execute();
		if(items!=null && items.size()>0)
		{
			log.exiting(RendererController.class.getName(), "findItem");
			return (RssItemEntity)items.get(0);
		}
		log.exiting(RendererController.class.getName(), "findItem");
		return null;
	}
	/**
	 * Get models
	 * @return
	 */
	public List<RendererModel> getModels() {
		return models;
	}
}
